/*
Copyright 2010 Thomas W. Holtquist

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

using System;
using System.Collections;
using System.Threading;

using Microsoft.SPOT;
using Microsoft.SPOT.Presentation;
using Microsoft.SPOT.Presentation.Media;
using Microsoft.SPOT.Touch;

using Skewworks.Pyxis.Kernel;

namespace Skewworks.Pyxis.GUI.Controls
{

    public class scrollbar : MarshalByRefObject, IControl
    {

        #region Variables

        protected internal int _xOffset;        // Used for placement inside containers like forms & panels
        protected internal int _yOffset;        // Used for placement inside containers like forms & panels

        protected internal int _x;
        protected internal int _y;
        protected internal int _w;
        protected internal int _h;
        protected internal bool _visible = true;
        protected internal bool _enabled = true;
        private bool _mDown = false;
        private bool _gDown = false;
        protected internal IControl _parent;
        private bool _suspend = false;

        private int _min;
        private int _max;
        private int _val;
        private int _sml = 1;
        private int _lrg = 10;
        private Orientation _orientation;

        private rect _decRect;
        private rect _incRect;
        private rect _grpRect;
        private int _chgVal;
        private Thread _changer;

        private int _mY = 0;
        private int _mX = 0;

        #endregion

        #region Events

        public event OnTap tapEvent;

        /// <summary>
        /// Event for Taps
        /// </summary>
        /// <param name="sender"></param>
        protected virtual void OnTap(Object sender, point e)
        {
            if (tapEvent != null) tapEvent(sender, e);
        }

        #endregion

        #region Constructors

        public scrollbar(int x, int y, int size, Orientation orientation)
        {
            if (size < 40) size = 40;
            _orientation = orientation;
            _x = x;
            _y = y;
            if (orientation == Orientation.Horizontal)
            {
                _w = size;
                _h = 16;
            }
            else
            {
                _h = size;
                _w = 16;
            }

            _min = 0;
            _max = 100;
            _val = 0;
        }

        public scrollbar(int x, int y, int size, Orientation orientation, int Minimum, int Maximum)
        {
            if (size < 40) size = 40;
            _orientation = orientation;
            _x = x;
            _y = y;
            if (orientation == Orientation.Horizontal)
            {
                _w = size;
                _h = 16;
            }
            else
            {
                _h = size;
                _w = 16;
            }

            _min = Minimum;
            _max = Maximum;
            _val = 0;
        }

        public scrollbar(int x, int y, int size, Orientation orientation, int Minimum, int Maximum, int Value)
        {
            if (size < 40) size = 40;
            _orientation = orientation;
            _x = x;
            _y = y;
            if (orientation == Orientation.Horizontal)
            {
                _w = size;
                _h = 16;
            }
            else
            {
                _h = size;
                _w = 16;
            }

            _min = Minimum;
            _max = Maximum;
            _val = Value;
        }

        #endregion

        #region Touch Invokes

        public void TouchDown(object sender, point e)
        {
            _mDown = true;

            if (!_enabled) return; 
            if (_decRect.contains(e))
            {
                value = _val - _sml;
                _chgVal = -_sml;
                _changer = new Thread(AutoIncDec);
                _changer.Priority = ThreadPriority.AboveNormal;
                _changer.Start();
                return;
            }

            if (_incRect.contains(e))
            {
                value = _val + _sml;
                _chgVal = _sml;
                _changer = new Thread(AutoIncDec);
                _changer.Priority = ThreadPriority.AboveNormal;
                _changer.Start();
                return;
            }

            if (_grpRect.contains(e))
            {
                _mX = e.x;
                _mY = e.y;
                _gDown = true;
                return;
            }

            if (_orientation == Orientation.Horizontal)
            {
                value = _val + ((e.x < _grpRect.x) ? -_lrg : _lrg);
            }
            else
            {
                value = _val + ((e.y < _grpRect.y) ? -_lrg : _lrg);
            }

        }

        public void TouchUp(object sender, point e)
        {
            if (_mDown)
            {
                if (this.ScreenBounds.contains(e)) OnTap(this, new point(e.x - left, e.y - top));
                _mDown = false;
            }
            _gDown = false;
        }

        public void TouchMove(object sender, point e)
        {
            // Only respond if we have the gripper
            if (!_gDown) return;

            if (_orientation == Orientation.Horizontal)
            {
                // Calculate Value from New Position
                // Difference (DIF)         = current X - initial X
                // New X (NWX)              = (GripX + DIF) - left - 16 (remove offset left & dec button)
                // Slide Range (ASR)        = Width - 32 - GripWidth (32 for both buttons)
                // Percent of Slide (PoS)   = NWX / ASR
                // Value (VAL)              = ((max - min) * PoS) + min
                value = (int)((_max - _min) * ((float)((_grpRect.x + (e.x - _mX)) - left - 16) / (float)(_w - 32 - _grpRect.width))) + _min;
            }
            else
            {
                // Calculate Value from New Position
                // Difference (DIF)         = current Y - initial Y
                // New Y (NWY)              = (GripY + DIF) - top - 16 (remove offset top & dec button)
                // Slide Range (ASR)        = Height - 32 - GripHeight (32 for both buttons)
                // Percent of Slide (PoS)   = NWY / ASR
                // Value (VAL)              = ((max - min) * PoS) + min
                value = (int)((_max - _min) * ((float)((_grpRect.y + (e.y - _mY)) - top - 16) / (float)(_h - 32 - _grpRect.height))) + _min;
            }

            _mX = e.x;
            _mY = e.y;
        }

        #endregion

        #region  Properties

        public int minimum
        {
            get { return _min; }
            set
            {
                if (value >= _max) value = _max - 1;
                _min = value;
                Render(true);
            }
        }

        public int maximum
        {
            get { return _max; }
            set
            {
                if (value <= _min) value = _min + 1;
                _max = value;
                Render(true);
            }
        }

        public int value
        {
            get { return _val; }
            set
            {
                if (value < _min) value = _min;
                if (value > _max) value = _max;
                _val = value;
                Render(true);
            }
        }

        public int SmallChange
        {
            get { return _sml; }
            set
            {
                if (_sml == value) return;
                _sml = value;
                Render(true);
            }
        }

        public int LargeChange
        {
            get { return _lrg; }
            set
            {
                if (_lrg == value) return;
                _lrg = value;
                Render(true);
            }
        }

        public int x
        {
            get { return _x; }
            set { _x = value; if (_parent != null) _parent.Render(); }
        }

        public int y
        {
            get { return _y; }
            set { _y = value; if (_parent != null) _parent.Render(); }
        }

        public virtual int width
        {
            get { return _w; }
            set { _w = value; if (_parent != null) _parent.Render(); }
        }

        public virtual int height
        {
            get { return _h; }
            set
            {
                if (value < 30) value = 30;
                _h = value;
                if (_parent != null) _parent.Render();
            }
        }

        public bool visible
        {
            get { return _visible; }
            set { _visible = value; Render(true); }
        }

        public bool enabled
        {
            get { return _enabled; }
            set { _enabled = value; Render(true); }
        }

        public rect bounds
        {
            get { return new rect(_x, _y, _w, _h); }
        }

        public IControl parent
        {
            get { return _parent; }
            set { _parent = value; }
        }

        public rect ScreenBounds
        {
            get { return new rect(_x + _xOffset, _y + _yOffset, _w, _h); }
        }

        public bool suspended
        {
            get { return _suspend; }
            set
            {
                _suspend = value;
                if (!_suspend && _parent != null) _parent.Render();
            }
        }

        public int top
        {
            get { return _y + _yOffset; }
        }

        public int left
        {
            get { return _x + _xOffset; }
        }

        public bool PenDown
        {
            get { return _mDown; }
        }

        public PyxisAPI APIRef
        {
            get { return _parent.APIRef; }
        }

        public Bitmap ScreenBuffer
        {
            get { return (_parent == null) ? null : _parent.ScreenBuffer; }
        }

        #endregion

        #region Public Methods

        public void SetOffset(IControl sender, point e)
        {
            if (sender != parent) throw new Exception("Only a parent can set a child's offset");
            _xOffset = e.x;
            _yOffset = e.y;
        }

        #endregion

        #region GUI

        public void Render()
        {
            Render(false);
        }

        private void Render(bool flush)
        {
            if (_parent == null || _parent.ScreenBuffer == null || !_visible || _suspend) return;

            int iGripSize = 0;

            // Background is the same regardless of orientation
            _parent.ScreenBuffer.DrawRectangle(Colors.Black, 1, left, top, _w, _h, 0, 0, Colors.Gray, 0, 0, Colors.Gray, 0, 0, 256);

            if (_orientation == Orientation.Horizontal)
            {
                // Draw the Left/Right Buttons
                _parent.ScreenBuffer.DrawRectangle(Colors.Black, 1, left, top, 16, 16, 0, 0, Colors.DarkGray, 0, 0, Colors.DarkGray, 0, 0, 256);
                _parent.ScreenBuffer.DrawImage(left + 4, top + 4, Resources.GetBitmap(Resources.BitmapResources.left), 0, 0, 5, 9);
                _parent.ScreenBuffer.DrawRectangle(Colors.Black, 1, left + _w - 16, top, 16, 16, 0, 0, Colors.DarkGray, 0, 0, Colors.DarkGray, 0, 0, 256);
                _parent.ScreenBuffer.DrawImage(left + _w - 11, top + 4, Resources.GetBitmap(Resources.BitmapResources.right), 0, 0, 5, 9);

                // Update Rects
                // We do this every render incase our offset has changed
                _decRect = new rect(left, top, 16, 16);
                _incRect = new rect(left + _w - 16, top, 16, 16);

                // Calculate Gripper Size
                // Total Value Range (TVR)      = max - min
                // Total Travel Range (TTR)     = TVR / SmallChange
                // Available Grip Range (AGR)   = Size - 32
                // Grip Size                    = AGR - TTR
                iGripSize = (_w - 32) - ((_max - _min) / _sml);
                if (iGripSize < 8) iGripSize = 8;

                // Calculate Gripper left (remember we might change gripper size to meet minimum)
                // Available Draw Range (ADR)   = (Size - 32 - GripSize)
                // Percent of Total (PoT)       = (value - min) / (max - min)
                // Offset                       = ADR * PoT
                int iOffset = (int)((_w - 32 - iGripSize) * ((float)(_val - _min) / (float)(_max - _min)));

                // Draw the Gripper
                _parent.ScreenBuffer.DrawRectangle(Colors.Black, 1, iOffset + left + 16, top, iGripSize, 16, 0, 0, Colors.DarkGray, 0, 0, Colors.DarkGray, 0, 0, 256);
                _grpRect = new rect(iOffset + left + 16, top, iGripSize, 16);
            }
            else
            {
                // Draw the Up/Down Buttons
                _parent.ScreenBuffer.DrawRectangle(Colors.Black, 1, left, top, 16, 16, 0, 0, Colors.DarkGray, 0, 0, Colors.DarkGray, 0, 0, 256);
                _parent.ScreenBuffer.DrawImage(left + 4, top + 5, Resources.GetBitmap(Resources.BitmapResources.up), 0, 0, 9, 5);
                _parent.ScreenBuffer.DrawRectangle(Colors.Black, 1, left, top + _h - 16, 16, 16, 0, 0, Colors.DarkGray, 0, 0, Colors.DarkGray, 0, 0, 256);
                _parent.ScreenBuffer.DrawImage(left + 4, top + _h - 11, Resources.GetBitmap(Resources.BitmapResources.down), 0, 0, 9, 5);

                // Update Rects
                // We do this every render incase our offset has changed
                _decRect = new rect(left, top, 16, 16);
                _incRect = new rect(left, top + _h - 16, 16, 16);

                // Calculate Gripper Size
                // Total Value Range (TVR)      = max - min
                // Total Travel Range (TTR)     = TVR / SmallChange
                // Available Grip Range (AGR)   = Size - 32
                // Grip Size                    = AGR - TTR
                iGripSize = (_h - 32) - ((_max - _min) / _sml);
                if (iGripSize < 8) iGripSize = 8;

                // Calculate Gripper left (remember we might change gripper size to meet minimum)
                // Available Draw Range (ADR)   = (Size - 32 - GripSize)
                // Percent of Total (PoT)       = (value - min) / (max - min)
                // Offset                       = ADR * PoT
                int iOffset = (int)((_h - 32 - iGripSize) * ((float)(_val - _min) / (float)(_max - _min)));

                // Draw the Gripper
                _parent.ScreenBuffer.DrawRectangle(Colors.Black, 1, left, iOffset + top + 16, 16, iGripSize, 0, 0, Colors.DarkGray, 0, 0, Colors.DarkGray, 0, 0, 256);
                _grpRect = new rect(left, iOffset + top + 16, 16, iGripSize);
            }

            if (flush) _parent.ScreenBuffer.Flush(left, top, _w, _h);
        }

        #endregion

        #region Private Methods

        private void AutoIncDec()
        {
            int iWait = 750;
            while (_mDown)
            {
                Thread.Sleep(iWait);
                if (!_mDown) return;
                value = _val + _chgVal;
                switch (iWait)
                {
                    case 750:
                        iWait = 500;
                        break;
                    case 500:
                        iWait = 250;
                        break;
                    case 250:
                        iWait = 75;
                        break;
                }
            }
        }

        #endregion

    }

}
